package jmine.tec.services.integration;

import static jmine.tec.services.api.ActionsEnum.EXECUTAR;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import jmine.tec.di.annotation.Injected;
import jmine.tec.services.annotations.Execution;
import jmine.tec.services.annotations.Input;
import jmine.tec.services.annotations.ServiceImplementor;
import jmine.tec.services.api.RawInput;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import bancosys.tec.datadigester.DataDigesterController;
import bancosys.tec.services.ServicesIntegrationTestCase;

/**
 * Service that loads files during an integration test
 * 
 * @author lundberg
 */
@ServiceImplementor(action = EXECUTAR)
public class CargaArquivoService {

    private static final Log LOG = LogFactory.getLog(CargaArquivoService.class);

    private static final String FILE_CODE = "Código do arquivo";

    private static final String BASE_PATH = "Caminho base";

    private static final String RELATIVE_PATH = "Caminho relativo";

    private DataDigesterController controller;

    private String fileCode;

    /**
     * Processes a file
     * 
     * @throws Exception
     */
    @Execution
    public void execute(@Injected RawInput input) throws Exception {
        String basePath = input.getRaw(BASE_PATH);
        String relativePath = input.getRaw(RELATIVE_PATH);

        if (StringUtils.isBlank(basePath)) {
            basePath = input.getRaw(ServicesIntegrationTestCase.INTEGRATION_TEST_LOCATION_URL);
        }

        String msg = "Efetuando carga de arquivo. Caminho base: %s. Caminho relativo: %s. Código do arquivo: %s.";
        LOG.info(String.format(msg, basePath, relativePath, this.fileCode));

        URL baseRefURL = new URL(basePath + StringUtils.join(relativePath.split("/"), File.separator));
        this.controller.process(this.fileCode, relativePath, baseRefURL.openStream());
    }

    /**
     * @param controller the controller to set
     */
    @Injected
    public void setController(DataDigesterController controller) {
        this.controller = controller;
    }

    /**
     * @param url the url to set
     */
    @Input(fieldName = BASE_PATH, defaultValue = ServicesIntegrationTestCase.INTEGRATION_TEST_LOCATION_URL)
    public void setBasePath(String basePath) throws MalformedURLException {
    }

    /**
     * @param fileName the fileName to set
     */
    @Input(fieldName = RELATIVE_PATH)
    public void setRelativePath(String relativePath) {
    }

    /**
     * @param fileCode the fileCode to set
     */
    @Input(fieldName = FILE_CODE)
    public void setFileCode(String fileCode) {
        this.fileCode = fileCode;
    }

}
